package com.weixin.xplore.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import com.weixin.xplore.controller.domain.request.SysUserPageQueryRequest;
import com.weixin.xplore.dao.entity.IntegralRecord;
import com.weixin.xplore.dao.entity.SysUser;
import com.weixin.xplore.dao.service.IntegralRecordDaoService;
import com.weixin.xplore.page.PageList;
import com.weixin.xplore.service.SysUserBizService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

@Component
@RequiredArgsConstructor
public class UserIntegralClearJob {
    private final SysUserBizService sysUserBizService;
    private final IntegralRecordDaoService recordDaoService;

    // 计算距离下一年年末的毫秒数
    public long calculateDelayToNextYearEnd() {
        Calendar now = Calendar.getInstance();
        int nextYear = now.get(Calendar.YEAR) + 1;
        Calendar endOfNextYear = Calendar.getInstance();
        endOfNextYear.set(Calendar.YEAR, nextYear);
        endOfNextYear.set(Calendar.MONTH, Calendar.DECEMBER);
        endOfNextYear.set(Calendar.DAY_OF_MONTH, 31);
        endOfNextYear.set(Calendar.HOUR_OF_DAY, 23);
        endOfNextYear.set(Calendar.MINUTE, 59);
        endOfNextYear.set(Calendar.SECOND, 59);
        endOfNextYear.set(Calendar.MILLISECOND, 999);

        return endOfNextYear.getTimeInMillis() - now.getTimeInMillis();
    }

    // 模拟每年年末执行的任务
    @Scheduled(fixedRate = 366 * 24 * 60 * 60 * 1000, initialDelayString = "#{@userIntegralClearJob.calculateDelayToNextYearEnd()}")
    public void run() {
        repeatClear(1);
        System.out.println("回归积分");

    }

    public void repeatClear(Integer currentSize) {
        //会员期间积分不过期
        SysUserPageQueryRequest pageQueryRequest = new SysUserPageQueryRequest();
        pageQueryRequest.setPageIs(true);
        pageQueryRequest.setCurrent(currentSize);
        pageQueryRequest.setSize(100);
        List<SysUser> sysUsers = sysUserBizService.pageList(pageQueryRequest);
        if (CollUtil.isEmpty(sysUsers)) {
            return;
        }
        if (sysUsers instanceof PageList<SysUser> pageList) {
            long total = pageList.getTotal();
            long size = pageList.getSize();


        }
        for (SysUser sysUser : sysUsers) {
            Boolean isVip = sysUser.getIsVip();
            if (BooleanUtil.isTrue(isVip)) {
                continue;
            }
            Integer point = sysUser.getPoint();
            sysUser.clearPoint();
            sysUserBizService.update(sysUser);
            recordDaoService.saveLog(sysUser.getId(), 10, -Long.valueOf(point), "回归积分");
        }
        repeatClear(currentSize + 1);
    }
}
